package org.webcamp.email.services.impl;

import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.ui.velocity.VelocityEngineUtils;
import org.webcamp.email.services.EmailService;

public class EmailServiceImpl implements EmailService {

	private Logger log = Logger.getLogger(getClass());
	private MailSender mailSender;
	private SimpleMailMessage templateMessage;
	private VelocityEngine velocityEngine;

	public void setVelocityEngine(VelocityEngine velocityEngine) {
		this.velocityEngine = velocityEngine;
	}

	public void setMailSender(MailSender mailSender) {
		this.mailSender = mailSender;
	}

	public void setTemplateMessage(SimpleMailMessage templateMessage) {
		this.templateMessage = templateMessage;
	}

	@Override
	public void sendEmail(String email, String messageKey, Map<String, String> messageModel) {
		SimpleMailMessage msg = new SimpleMailMessage(templateMessage);
		msg.setTo(email);

		String text = VelocityEngineUtils.mergeTemplateIntoString(
				velocityEngine, "templates/" + messageKey + ".text.txt", messageModel);
		msg.setText(text);
		String subject = VelocityEngineUtils.mergeTemplateIntoString(
				velocityEngine, "templates/" + messageKey + ".subject.txt", messageModel);
		msg.setSubject(subject);
		try {
			mailSender.send(msg);
		} catch (MailException ex) {
			ex.printStackTrace();
			log.error("Cannot send email message", ex);
		}
	}

}
